package com.kalvan.admin.system.controller;


import com.kalvan.admin.system.service.AuthService;
import com.kalvan.commons.constant.LogGroup;
import com.kalvan.commons.vo.system.UserInfoVO;
import com.kalvan.commons.vo.system.UserVO;
import com.kalvan.web.log.LogType;
import com.kalvan.web.log.annotation.SysLog;
import com.kalvan.web.servlet.annotation.TokenCheck;
import com.kalvan.web.servlet.interceptor.CallInterfaceInterceptor;
import com.kalvan.web.servlet.response.R;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.constraints.NotBlank;

/**
 * 登录鉴权接口
 *
 * @author kalvan
 * @date 2020/7/26
 **/
@SysLog(group = LogGroup.AUTH)
@RestController
@RequestMapping("auth")
public class AuthController {
    @Resource
    private AuthService authService;

    @ApiOperation(value = "登录", notes = "登录", response = R.class)
    @SysLog(remark = "用户登录", type = LogType.LOGIN)
    @TokenCheck(required = false)
    @PostMapping("login")
    public R login(@ApiParam(value = "username", name = "username") @NotBlank(message = "登录账号不能为空") String username,
                   @ApiParam(value = "password", name = "password") @NotBlank(message = "登录密码不能为空") String password) {
        try {
            //初始化登录用户
            CallInterfaceInterceptor.setUserName(username);
            UserVO userVO = authService.login(username, password);
            return R.ok().putData(userVO);
        } catch (Exception e) {
            return R.error(e.getMessage());
        }
    }

    @ApiOperation(value = "查询用户菜单权限", notes = "查询用户菜单权限", response = R.class)
    @GetMapping("info")
    public R info() {
        UserVO userVO = (UserVO) CallInterfaceInterceptor.getUserInfo();
        UserInfoVO userInfoVO = new UserInfoVO();
        userInfoVO.setCode(authService.selectCodeByUserId(userVO.getId()));
        userInfoVO.setPermissions(authService.selectMenuByUserId(userVO.getId()));
        userInfoVO.setUser(userVO);
        return R.ok().putData(userInfoVO);
    }

    @ApiOperation(value = "注销登录", notes = "注销登录", response = R.class)
    @SysLog(remark = "用户注销登录", type = LogType.LOGIN)
    @TokenCheck(required = false)
    @PostMapping("logout")
    public R logout() {
        return R.ok();
    }

}
